package com.web.email;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.app.AppContext;

public class EmailParser {

	private static final String EMAIL_FOLDER_PATH = AppContext.getProperty("email.template.path");
	
	private String fileName;
	
	public EmailParser(String fileName){
		
		this.fileName = fileName;
	}
	
	public String getParsedContent(Map<String, String> values){
		
		String content = readFileContent();
		
		return getWithReplacements(content, values);
	}
	
	private String readFileContent(){
		
		StringBuffer str = new StringBuffer();
		
		try{

			FileInputStream fstream = new FileInputStream(EMAIL_FOLDER_PATH + fileName);
	
			DataInputStream in = new DataInputStream(fstream);
			  
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
		  
			String strLine;
			
			while ((strLine = br.readLine()) != null)   {
		  
				str.append(strLine + "\n");
			}
		
			in.close();
		    
		}catch (Exception e){
		  
			throw new IllegalStateException("Couldn't read file content", e);
		}
		return str.toString();
	}
	
	private String getWithReplacements(String line, Map<String, String> varValues){
		
		List<String> vars = getVariables(line);
		
		String replacedLine = line;
		
		for(String var: vars){
			
			String value = null;
			
			if(varValues.containsKey(var)){
			
				value = varValues.get(var);
			}
			else if(AppContext.containsProperty(var)){
				
				value = AppContext.getProperty(var);
			}
			
			if(value != null){
			
				replacedLine = replacedLine.replaceAll("\\{" + var + "\\}", value);
			}
		}
		
		return replacedLine;
	}
	
	private List<String> getVariables(String strLine) {
		
		List<String> vars = new ArrayList<String>();
		
		String[] splitLine = strLine.split("\\{");
		
		for(int i = 1; i < splitLine.length; i++){
			
			String[] splitVars = splitLine[i].split("\\}");
			
			if(!vars.contains(splitVars[0])){
			
				vars.add(splitVars[0]);
			}
		}
		return vars;
	}
}
